//index.js
//获取应用实例
import {typeWord, fetch} from '../../../utils/index.js';
var app = getApp();
let timer;

Page({
    data: {
        game_id: 0,
        step: 1,
        motto: '欢迎参加《消失的爱人》侦探推理剧',
        userInfo: {},
        gameInfo: null,
        showTitle: '',
        photos: [],
        canIUse: wx.canIUse('longpress'),
        showNext: true,
        players: [],
        voteModal: false,
        thisFilePath: '',
        myVotes: 0,
        myRole: {}
    },
    /**
   * 用户点击右上角分享
   */
    // onShareAppMessage: function() {
    //     return {title: '我在BunnyClub参加侦探剧！你也一起来玩吧', path: '/pages/index/index', imageUrl: this.data.thisFilePath}
    // },
    swipe: function(event) {
        if (event.detail.current < 12) {
            this.setData({showNext: true});
        } else {
            this.setData({showNext: false});
        }
    },

    onLoad: function(query) {
        const that = this;
        //调用应用实例的方法获取全局数据
        that.setData({game_id: query.id});
        if (app.globalData.userInfo) {
            that.initPage();
        } else {
            app.login(that.initPage.bind(that));
        }
        wx.onUserCaptureScreen(function(res) {
            wx.showModal({title: '警告！', content: '为了游戏体验和公平性，请勿截图！', confirmText: '确定', showCancel: false})
        });

    },
    onUnload: function() {
        clearInterval(timer);
    },
    initPage: function() {
        const that = this;
        that.getGameInfo().then(() => {
            clearInterval(timer);
            that.setData({userInfo: app.globalData.userInfo});
            that.getGameStatus();
            timer = setInterval(that.getGameStatus, 10000);
        });

    },

    getGameInfo: function() {

        const that = this;
        return fetch.post('game/get_game', {game_id: this.data.game_id}).then(function(res) {
            that.setData({gameInfo: res});
            switch (res.game.status.toString()) {
                case '1':
                    that.showHello();
                    break;
                default:
                    break;
            }
            fetch.post('game/get_proofs', {
                game_id: that.data.game_id,
                player_id: res.player.id
            }).then(function(res) {
                that.setData({photos: res.list});
            });
        });

    },
    getGameStatus: function() {
        const that = this;
        const {step} = this.data;
        fetch.post('game/get_game_status', {
            game_id: this.data.game_id
        }, true).then(function(res) {
            if (step != res.status) {
                that.setData({step: res.status});
                that.getGameInfo();
                if (res.status <= 0) {
                    that.getVoteResult().then(() => {
                        that.shareResult();
                    });
                }
            }
        });
    },
    showHello: function() {
        const that = this;
        const {showTitle, gameInfo} = that.data;
        typeWord("欢迎加入《" + gameInfo.game.title + "》侦探推理剧", function(word) {
            that.setData({showTitle: word});
        });

    },
    previewPhoto: function(event) {
        wx.previewImage({
            current: event.target.dataset.photo.image_url,
            urls: this.data.photos.map((photo) => {
                return photo.image_url;
            })
        });
    },
    deletePhoto: function(event) {
        const that = this;
        let {photos} = that.data;
        const photo = event.target.dataset.photo;
        wx.showActionSheet({
            itemList: ['删除'],
            itemColor: '#FF0000',
            success: function(res) {
                if (res.tapIndex === 0) {
                    fetch.post('game/del_proof', {proof_id: photo.id}).then(function(res) {
                        photos = photos.filter(function(_p) {
                            return _p.id != photo.id;
                        });
                        that.setData({photos: photos});
                    });
                }
            }
        });
    },
    votePlayer: function(event) {
        const {game_id} = this.data;
        const player_id = event.target.dataset.player_id;
        fetch.post('game/vote', {
            game_id: game_id,
            to_player: player_id
        }).then(function(res) {
            wx.showModal({title: '提示', content: '投票成功', confirmText: '确定', showCancel: false})
        });
    },
    voteModalHide: function() {
        this.setData({voteModal: false});
    },
    //投票
    vote: function() {
        const that = this;
        const {game_id} = this.data;
        fetch.post('game/get_game_players', {
            game_id: that.data.game_id
        }, true).then(function(res) {
            const players = res;
            that.setData({players: players, voteModal: true});
            // wx.showActionSheet({
            //   itemList: players.map((player) => {
            //     return player.role_name;
            //   }),
            //   success: function (res2) {
            //
            //   }
            // })
        });

    },
    //事件处理函数
    takePhoto: function() {
        const that = this;
        let {photos} = that.data;

        wx.chooseImage({
            count: 10 - photos.length,
            success: function(res) {
                res.tempFilePaths.forEach((filePath) => {
                    wx.uploadFile({
                        url: fetch.domain + 'qiniu/upload_photo',
                        formData: {
                            'access_token': wx.getStorageSync('WeixinAppThirdSession'),
                            'game_id': that.data.game_id
                        },
                        name: 'key',
                        filePath: filePath,
                        success: function(res) {
                            const result = JSON.parse(res.data);
                            if (result.status > 0) {
                                const {photos} = that.data;
                                that.setData({
                                    photos: photos.concat(result.data)
                                })
                            }
                        }
                    });
                });
            }
        });
    },

    getVoteResult: function() {
        const that = this;
        const {game_id} = this.data;
        return fetch.post('game/vote_result', {game_id: game_id}).then(function(voteInfo) {
            const myVotes = voteInfo.votes.length;
            const humanMap = {
                0: {
                    role: '影帝',
                    content: '全世界欠你一个小金人'
                },
                1: {
                    role: '戏精',
                    content: '人生如戏 浑身都是戏'
                },
                2: {
                    role: '演员',
                    content: '该配合你演出的我演视而不见'
                },
                3: {
                    role: '临时演员',
                    content: '送你《演员的自我修养》，好好修炼！'
                }
            };
            let myRole = {};
            Object.keys(humanMap).forEach(function(key) {
                if (myVotes >= key) {
                    myRole = humanMap[key];
                }
            });
            that.setData({myRole, myVotes});
        });
    },
    shareResult: function() {
        const that = this;
        const {userInfo, gameInfo, myRole, myVotes} = this.data;
        var ctx = wx.createCanvasContext('secondCanvas');
        var width = wx.getSystemInfoSync().windowWidth;
        var rate = width / 355;
        var height = 667 * 355 / 375 * rate;
        // this.setData({ height: height });
        // Create linear gradient
        console.log(userInfo.avatarUrl);
        wx.downloadFile({
            url: userInfo.avatarUrl,
            success: function(res) {
                ctx.drawImage('./img/bg.jpg', 0, -97 * rate, width, height);

                ctx.setFontSize(40 * rate);
                ctx.setTextBaseline('top');
                ctx.setTextAlign('center');
                ctx.setFillStyle('white');
                ctx.fillText('侦探推理剧', 1 / 2 * width, 30 * rate);

                ctx.setFontSize(16 * rate);
                ctx.setTextBaseline('top');
                ctx.setTextAlign('center');
                ctx.setFillStyle('white');
                ctx.fillText("恭喜                         在本轮阿姨歌星中", (width / 2), 65 * rate);

                ctx.setTextAlign('center');
                ctx.setFillStyle('#FE1E91');
                ctx.fillText(userInfo.nickName, (width / 2 - 50 * rate), 65 * rate);

                ctx.setFontSize(20 * rate);
                ctx.setTextBaseline('top');
                ctx.setTextAlign('center');
                ctx.setFillStyle('white');
                ctx.fillText("在BunnyClub侦探剧【" + gameInfo.game.title + '】中', (width / 2), 120 * rate);

                ctx.setFontSize(18 * rate);
                ctx.setTextBaseline('top');
                ctx.setTextAlign('left');
                ctx.setFillStyle('white');
                ctx.fillText("仅引起", 90 * rate, 364 * rate);
                ctx.fillText("位小伙伴怀疑", 170 * rate, 364 * rate);

                ctx.setFontSize(24 * rate);
                ctx.setTextAlign('center');
                ctx.setFillStyle('#FE1E91');
                ctx.fillText(myVotes, 158 * rate, 360 * rate);

                ctx.setTextBaseline('bottom');
                ctx.setFontSize(48 * rate);
                ctx.setTextAlign('left');
                ctx.setFillStyle('#FE1E91');
                ctx.fillText(myRole.role, width / 2, 450 * rate);

                ctx.setTextBaseline('bottom');
                ctx.setFontSize(18 * rate);
                ctx.setTextAlign('center');
                ctx.setFillStyle('white');
                ctx.fillText(myRole.content, width / 2, 475 * rate);

                ctx.setFontSize(18 * rate);
                ctx.setTextAlign('right');
                ctx.setFillStyle('white');
                ctx.fillText("演技堪比 ", width / 2, 439 * rate);

                ctx.save();
                ctx.beginPath();
                ctx.arc(177 * rate, 140 * rate, 100 / 2 * rate, 0, 2 * Math.PI);
                if (ctx.clip) 
                    ctx.clip();
                ctx.drawImage(res.tempFilePath, 127 * rate, 90 * rate, 100 * rate, 100 * rate);
                ctx.restore();
                ctx.draw();

                wx.canvasToTempFilePath({
                    canvasId: 'secondCanvas',
                    success: function(res) {
                        that.setData({thisFilePath: res.tempFilePath});
                    }
                })
            },
            fail: function(err) {
                console.log(err)
            }
        })
    },

    drawResult: function() {
        const that = this;
        const {userInfo, gameInfo, game_id, myRole, myVotes} = this.data;
        var ctx = wx.createCanvasContext('firstCanvas');
        var width = wx.getSystemInfoSync().windowWidth;
        var rate = width / 375;
        var height = 667 * rate;
        this.setData({height: height});
        const url = fetch.domain + 'weixin/qrcode' + '?scene=1';
        console.log(url);
        wx.downloadFile({
            url: url,
            success: function(res2) {
                wx.downloadFile({
                    url: userInfo.avatarUrl,
                    success: function(res) {
                        ctx.drawImage('./img/bg.jpg', 0, 0, width, height);
                        ctx.drawImage('./img/finger@2x.png', 135 * rate, 476 * rate, 105 * rate, 105 * rate);

                        ctx.setFontSize(40 * rate);
                        ctx.setTextBaseline('top');
                        ctx.setTextAlign('center');
                        ctx.setFillStyle('white');
                        ctx.fillText('侦探推理剧', 1 / 2 * width, 30 * rate);

                        ctx.setFontSize(20 * rate);
                        ctx.setTextAlign('center');
                        ctx.setFillStyle('#FE1E91');
                        ctx.fillText(userInfo.nickName, width / 2, 90 * rate);

                        ctx.setFontSize(20 * rate);
                        ctx.setTextBaseline('top');
                        ctx.setTextAlign('center');
                        ctx.setFillStyle('white');
                        ctx.fillText("在BunnyClub侦探剧【" + gameInfo.game.title + '】中', (width / 2), 120 * rate);

                        ctx.setFontSize(18 * rate);
                        ctx.setTextBaseline('top');
                        ctx.setTextAlign('left');
                        ctx.setFillStyle('white');
                        ctx.fillText("仅引起", 90 * rate, 364 * rate);
                        ctx.fillText("位小伙伴怀疑", 170 * rate, 364 * rate);

                        ctx.setFontSize(24 * rate);
                        ctx.setTextAlign('center');
                        ctx.setFillStyle('#FE1E91');
                        ctx.fillText(myVotes, 158 * rate, 360 * rate);

                        ctx.setTextBaseline('bottom');
                        ctx.setFontSize(48 * rate);
                        ctx.setTextAlign('left');
                        ctx.setFillStyle('#FE1E91');
                        ctx.fillText(myRole.role, width / 2, 450 * rate);

                        ctx.setTextBaseline('bottom');
                        ctx.setFontSize(18 * rate);
                        ctx.setTextAlign('center');
                        ctx.setFillStyle('white');
                        ctx.fillText(myRole.content, width / 2, 475 * rate);

                        ctx.setFontSize(18 * rate);
                        ctx.setTextAlign('right');
                        ctx.setFillStyle('white');
                        ctx.fillText("演技堪比 ", width / 2, 439 * rate);

                        ctx.setFontSize(18 * rate);
                        ctx.setTextBaseline('top');
                        ctx.setTextAlign('center');
                        ctx.fillText("长按识别小程序，BunnyClub试试演技", width / 2, 593 * rate);

                        ctx.setFontSize(10 * rate);
                        ctx.setTextBaseline('top');
                        ctx.setTextAlign('right');
                        ctx.fillText("BunnyClub特发此证，以资鼓励", width - 20 * rate, height - 20 * rate);

                        ctx.save();
                        ctx.beginPath();
                        ctx.arc(186 * rate, 256 * rate, 132 / 2 * rate, 0, 2 * Math.PI);

                        if (ctx.clip) 
                            ctx.clip();
                        ctx.drawImage(res2.tempFilePath, 120 * rate, 190 * rate, 132 * rate, 132 * rate);
                        ctx.restore();

                        ctx.save();
                        ctx.beginPath();
                        ctx.arc(186 * rate, 256 * rate, 60 / 2 * rate, 0, 2 * Math.PI);
                        if (ctx.clip) 
                            ctx.clip();
                        ctx.drawImage(res.tempFilePath, 156 * rate, 226 * rate, 60 * rate, 60 * rate);
                        ctx.restore();
                        ctx.draw();

                        setTimeout(() => {
                            wx.canvasToTempFilePath({
                                canvasId: 'firstCanvas',
                                success: function(res) {
                                    wx.previewImage({
                                        urls: [res.tempFilePath]
                                    })
                                }
                            })
                        }, 1000);

                    },

                    fail: function(err) {
                        console.log(err)
                    }
                });
            },
            fail: function(err) {
                console.log(err)
            }
        });
    }
})
